package com.cyt.sys.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加密算法工具类
 *
 * Created by dingxu on 2019/4/8.
 */
public class RSAHelper {
    private static String NUM_DES_CUT="7";
    private static String PREFIX_CIPHER="MIGfA0G";

    /**
     * 得到公钥
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 得到私钥
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key,String password) throws Exception {
        key=DESHelper.decryptor(key,password);
        String  keyN=key.substring(7, key.length() -1);
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(keyN);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 得到公钥字符串（经过base64编码）
     * @return
     */
    public static String getKeyPubliceString(Key key) throws Exception {
        byte[] keyBytes = key.getEncoded();
        String s =new BASE64Encoder().encode(keyBytes);
        return s;
    }

    /**
     * 得到私钥字符串（经过base64编码）
     * @return
     */
    public static String getKeyPrivateString(Key key,String password) throws Exception {
        byte[] keyBytes = key.getEncoded();
        String s = (new BASE64Encoder()).encode(keyBytes);
        return DESHelper.encrypt(PREFIX_CIPHER+s+NUM_DES_CUT,password);
    }

/*    public static void main(String[] args) throws Exception {

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        //密钥位数
        keyPairGen.initialize(1024);
        //密钥对
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // 私钥
        PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        String publicKeyString = getKeyPubliceString(publicKey);
        System.out.println("public:\n" + publicKeyString);

        String privateKeyString = getKeyPrivateString(privateKey);
        System.out.println("private:\n" + privateKeyString);

        //加解密类
        Cipher cipher = Cipher.getInstance("RSA");//Cipher.getInstance("RSA/ECB/PKCS1Padding");

        //明文
        byte[] plainText = "我们都很好！邮件：@sina.com".getBytes();

        //加密
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] enBytes = cipher.doFinal(plainText);

       //通过密钥字符串得到密钥
        publicKey = getPublicKey(publicKeyString);
        privateKey = getPrivateKey(privateKeyString);

        //解密
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[]deBytes = cipher.doFinal(enBytes);

        publicKeyString = getKeyPubliceString(publicKey);
        System.out.println("public:\n" +publicKeyString);

        privateKeyString = getKeyPrivateString(privateKey);
        System.out.println("private:\n" + privateKeyString);

        String s = new String(deBytes);
        System.out.println(s);

    }*/


    /**
     * 得到私钥字符串（经过base64编码）
     * @return
     */
    public static KeyPair getPublicKeyAndPrivateKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        //密钥位数
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();;
        return keyPair;
    }

    /**
     * 加密字符串
     * @param publicKeyString 公钥
     * @param content 加密内容
     * @return
     */
    public static String encodeString(String publicKeyString,String content) throws Exception {
        if(content==null||content.equals("")){
            return "";
        }else{
            Cipher cipher = Cipher.getInstance("RSA");
            PublicKey publicKey=getPublicKey(publicKeyString);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] enBytes = cipher.doFinal(content.getBytes());
            return new BASE64Encoder().encode(enBytes);
        }

    }

    /**
     * 解密字符串
     * @param privateKeyString 私钥
     * @param content 加密内容
     * @return
     */
    public static String decodeString(String privateKeyString,String content,String password) throws Exception {
        if(content==null||content.equals("")){
            return "";}
        else{
            byte[]deBytess =new BASE64Decoder().decodeBuffer(content);
            Cipher cipher = Cipher.getInstance("RSA");
            PrivateKey privateKey1=getPrivateKey(privateKeyString,password);
            cipher.init(Cipher.DECRYPT_MODE, privateKey1);
            byte[]deBytes = cipher.doFinal(deBytess);
            return new String(deBytes);
        }

    }


    public static void main(String[] args) throws Exception {

        byte[] plainText = "团结奋进、大胆创新,智享未来，砥志研思".getBytes();

        String s =new String(plainText);

        String privateKeyString="1vP0B2ZgPN5B6D6nkR5SM4QEprFeFQ2HIJCj2xqMSfHaU+ZDTrjOHtX9C6pK81/9cHJgpBNjKbnR\n" +
                "n+K9fTVtU5NszlsNfOaVhUmVIfI7EnGp/d8Gp6WDUQ6CmwSdb76/id6J7mnxJAc7Ll8m+SoP2KLI\n" +
                "ylKhhVrg1zWhqxzKrZbfjjeZPMwvDlXEb/15436Ypkkdoed/+Sd1P+boV3OdbCp9wp5NjEk04rjY\n" +
                "pxdSa+S2PoOwMzzXCfla6pbCEyKU+F0yOwBxA7gCLQ1Y7bQXr8bL1HP6HYpjeVfYvRulsM0tjNTM\n" +
                "k8n/yPOLxEvesFBaRTUTy0WoiXYsQqGdDgVihKBz1dJ0HRuQqCU192RTuAgli8thTUH2kvqauRX1\n" +
                "XGIjZNeCPhT+MgqxsDjaQ7oiv8vMsD64Hfo/N727zMNiH+gqm4heTJ8Mtpj+0AFlHPWWN5yQ5mOA\n" +
                "Y7z6AY8volXsQ0+giJnUvMnLmQBQRiUuC0TQGvdWT6ZKirKJcIWXRkUm6M72QhmA60DVx6UMcAwL\n" +
                "SXWqO8iNssS9DrrSTUllTwU6E65aFBaUKZsWt7Ekm7oayt3nylwSSGVKeylwE1MTMCmNB9LieHGI\n" +
                "tFvvDDeRkCWLwb224b+N90CWJbiXeXDq9XYR15JWeqFqhP8bX1hw4LWY1JOkwaDNjYY5VS0HuYCs\n" +
                "UbL7A156oAO6viNbYjL3N8Gb3A0lhnjBBgLh5gJV/smPZ5izcU0U0EAKEvECvlsowFY5AtQv/XwF\n" +
                "Avgr8nLbJLD2CoQtFOg23hMXsAcIIfnrHJmyWcEfADDPSYcwwbr0By5epblEnWaxfO+1Lt9iKWoZ\n" +
                "kcH2P1hI7Sj4YrSGh5689kzzr8EXBkYclnmR/gF5JxXmRi/6ApP/P4nBjd6/JesELtwMkmww+ktr\n" +
                "WLpghK1bk7sc21ihcZFijp/6VtT0iZ68z0lSNix3bWHR42nM02iV5gO0C8jRurNtyKfypQfC0OYS\n" +
                "0WfDkBOfYqHSqckmnM3SGc52YIeqnUieuYad0iygBHTlaiiAEUOL0bxoLw8ZF6NUird5KJYy89m+\n" +
                "1PlbA3d5xAV8xAjm01POLN1W87qhw5S9nGMwVlNUVg1ASqkjHGc9iztd6sY/AKZPeKHkOVBF59Mi\n" +
                "W6PS9tyqAWTtFeejUg4Dqo0fo3UljHxFUw==";
        //公钥字符串
        String publicKeyString="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvR3yqx/1ewx68/WgF78/GKDTqZK+zjB2VXJOT\n" +
                "Ont+lLndW9PlzXSJjQpMfhHJv+IK/WmVm/OPXlCSJttnlhH6hBKoPOc936tewohZjYhxnhAQfg/j\n" +
                "YJNSoskLTs8iJjY4ZL/ehSKjoxY1lmNXMkMC/+wCSBszyDfPejCsVsVxpwIDAQAB";
        String password="9998877";
        //加密
        String enBytes=encodeString(publicKeyString,s);
        //解密
        String deBytes=decodeString(privateKeyString,enBytes,password);


        System.out.println(deBytes);

    }

}
